package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.pojo.dto.MsgGetHtmlDTO;
import com.xbongbong.paas.pojo.dto.MsgGetReceiptStatusDTO;
import com.xbongbong.paas.pojo.dto.MsgHaveReadDTO;
import com.xbongbong.paas.pojo.dto.MsgReceiptSaveDTO;
import com.xbongbong.paas.pojo.dto.MsgSurveyHasAnswerDTO;
import com.xbongbong.paas.pojo.dto.MsgSurveySaveDTO;
import com.xbongbong.paas.pojo.vo.MsgGetHtmlVO;
import com.xbongbong.paas.pojo.vo.MsgGetReceiptStatusVO;
import com.xbongbong.paas.pojo.vo.MsgHaveReadVO;
import com.xbongbong.paas.pojo.vo.MsgReceiptSaveVO;
import com.xbongbong.paas.pojo.vo.MsgSurveyHasAnswerVO;
import com.xbongbong.paas.pojo.vo.MsgSurveySaveVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.domain.entity.MsgLogEntity;
import com.xbongbong.saas.domain.entity.MsgTemplateEntity;
import com.xbongbong.saas.domain.entity.SurveyAnswerEntity;
import com.xbongbong.saas.domain.entity.SurveyAnswerUserEntity;
import com.xbongbong.saas.model.MsgLogModel;
import com.xbongbong.saas.model.MsgTemplateModel;
import com.xbongbong.saas.model.SurveyAnswerModel;
import com.xbongbong.saas.model.SurveyAnswerUserModel;
import com.xbongbong.saas.service.AdminMsgService;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * admin中的消息操作
 * 创建时间 2019/4/16 10:16 AM
 * 修改时间 2019/4/16 10:16 AM
 * @author chy
 * @since v1.0
 * @version v1.0
 */
@Service("adminMsgService")
public class AdminMsgServiceImpl implements AdminMsgService {

    @Resource
    private MsgLogModel msgLogModel;
    @Resource
    private UserModel userModel;
    @Resource
    private MsgTemplateModel msgTemplateModel;
    @Resource
    private SurveyAnswerUserModel surveyAnswerUserModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private SurveyAnswerModel surveyAnswerModel;
    @Override
    public MsgReceiptSaveVO receiptSave(MsgReceiptSaveDTO msgReceiptSaveDTO) throws XbbException {
        MsgReceiptSaveVO msgReceiptSaveVO = new MsgReceiptSaveVO();
        Integer msgLogId = msgReceiptSaveDTO.getMsgLogId();
        String corpid = msgReceiptSaveDTO.getCorpid();
        String userId = msgReceiptSaveDTO.getUserId();
        JSONObject receiptObject = msgReceiptSaveDTO.getReceiptObject();
        MsgLogEntity msgLog = msgLogModel.getByKey(msgLogId, corpid);

        if(msgLog == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, I18nStringConstant.SENDING_MESSAGE_DOES_EXIST);
        }

        //当前操作人和发送目标对象不一致
        if(!Objects.equals(userId, msgLog.getUserId())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, I18nStringConstant.THE_RECIPIENT_AND_THE_SENDER_INCONSISTENT);
        }

        msgLog.setHaveReceipt(1);
        msgLog.setReceiptInfo(receiptObject.toJSONString());
        msgLog.setReceiptTime(DateTimeUtil.getInt());
        msgLog.setUpdateTime(DateTimeUtil.getInt());
        msgLogModel.save(msgLog);
        return msgReceiptSaveVO;
    }

    @Override
    public MsgHaveReadVO haveRead(MsgHaveReadDTO msgHaveReadDTO) throws XbbException {

        MsgHaveReadVO msgHaveReadVO = new MsgHaveReadVO();

        String userId = msgHaveReadDTO.getUserId();
        String corpid = msgHaveReadDTO.getCorpid();
        Integer msgLogId = msgHaveReadDTO.getMsgLogId();
        UserEntity user = userModel.getByKey(userId, corpid);

        if(user == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100013, I18nStringConstant.LOGIN_USER_DOES_NOT_EXIST);
        }

        MsgLogEntity msgLog = msgLogModel.getByKey(msgLogId, corpid);
        if(msgLog == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, I18nStringConstant.SENDING_MESSAGE_DOES_EXIST);
        }

        //当前操作人和发送目标对象不一致
        if(!Objects.equals(userId, msgLog.getUserId())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, I18nStringConstant.INCONSISTENT_READER_AND_SENDER);
        }

        msgLog.setHaveRead(1);
        msgLog.setUpdateTime(DateTimeUtil.getInt());
        msgLogModel.save(msgLog);
        return msgHaveReadVO;
    }

    @Override
    public MsgGetHtmlVO getHtml(MsgGetHtmlDTO msgGetHtmlDTO) throws XbbException {
        MsgGetHtmlVO msgGetHtmlVO = new MsgGetHtmlVO();
        String corpid = msgGetHtmlDTO.getCorpid();
        Integer msgLogId = msgGetHtmlDTO.getMsgLogId();
        MsgLogEntity msgLog = msgLogModel.getByKey(msgLogId, corpid);
        if(msgLog == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, I18nStringConstant.SENDING_MESSAGE_DOES_EXIST);
        }
        Integer templateId = msgLog.getTemplateId();

        JSONObject json = getHtml(templateId);

        String html = json.getString("html");
        String javaScript = json.getString("javaScript");

        msgGetHtmlVO.setHtml(html);
        msgGetHtmlVO.setJavaScript(javaScript);
        return msgGetHtmlVO;
    }

    private JSONObject getHtml(Integer templateId) throws XbbException {
        MsgTemplateEntity msgTemplate = msgTemplateModel.getByKey(templateId);

        if(msgTemplate == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, I18nStringConstant.MESSAGE_TEMPLATE_DOES_NOT_EXIST);
        }

        String html = msgTemplate.getHtml();
        String javaScript = msgTemplate.getJavaScript();

        JSONObject json = new JSONObject();
        json.put("html", html);
        json.put("javaScript", javaScript);
        return json;
    }

    @Override
    public MsgGetReceiptStatusVO getReceiptStatus(MsgGetReceiptStatusDTO msgGetReceiptStatusDTO) throws XbbException {
        MsgGetReceiptStatusVO msgGetReceiptStatusVO = new MsgGetReceiptStatusVO();
        Integer msgLogId = msgGetReceiptStatusDTO.getMsgLogId();
        String corpid = msgGetReceiptStatusDTO.getCorpid();

        MsgLogEntity msgLog = msgLogModel.getByKey(msgLogId, corpid);
        if(msgLog == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, I18nStringConstant.SENDING_MESSAGE_DOES_EXIST);
        }
        msgGetReceiptStatusVO.setHaveReceipt(msgLog.getHaveReceipt());
        msgGetReceiptStatusVO.setHaveRead(msgLog.getHaveRead());
        return msgGetReceiptStatusVO;
    }

    @Override
    public MsgSurveyHasAnswerVO hasAnswer(MsgSurveyHasAnswerDTO msgSurveyHasAnswerDTO) throws XbbException {
        MsgSurveyHasAnswerVO msgSurveyHasAnswerVO = new MsgSurveyHasAnswerVO();

        String corpid = msgSurveyHasAnswerDTO.getCorpid();
        String userId = msgSurveyHasAnswerDTO.getUserId();

        boolean hasAnswer = false;
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("userId", userId);
        param.put("del", 0);
        Integer count = surveyAnswerUserModel.getEntitysCount(param);
        if(count > 0){
            hasAnswer = true;
        }
        msgSurveyHasAnswerVO.setHasAnswer(hasAnswer);
        return msgSurveyHasAnswerVO;
    }

    @Override
    public MsgSurveySaveVO surveySave(MsgSurveySaveDTO msgSurveySaveDTO) throws XbbException {
        Integer surveyId = msgSurveySaveDTO.getSurveyId();
        String surveyName = I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_SATISFACTION_SURVEY_OF_MARKETING);
        Integer sysUserId = 0;
        String sysUserName = "";
        String corpid = msgSurveySaveDTO.getCorpid();
        String corpName = "";
        CompanyEntity company = companyModel.getByKey(corpid);
        if (company != null) {
            corpName = company.getCorpName();
        }
        String userId = msgSurveySaveDTO.getUserId();
        String userName = "";
        if (!StringUtil.isEmpty(corpid) && !StringUtil.isEmpty(userId)) {
            UserEntity user = userModel.getByKey(userId, corpid);
            if (user != null) {
                userName = user.getName();
            }
        }
        SurveyAnswerUserEntity surveyAnswerUser = new SurveyAnswerUserEntity(surveyId, surveyName, sysUserId, sysUserName, corpid, corpName, userId, userName);
        surveyAnswerUserModel.save(surveyAnswerUser);


        List<MsgSurveySaveDTO.Answer> answers = msgSurveySaveDTO.getAnswers();
        List<SurveyAnswerEntity> list = new ArrayList<>();
        for(MsgSurveySaveDTO.Answer answer : answers){
            Integer questionId = answer.getQuestionId();
            String answerStr = answer.getAnswer();
            String memo = answer.getMemo();
            SurveyAnswerEntity surveyAnswer = new SurveyAnswerEntity(surveyAnswerUser, questionId, answerStr, memo);
            list.add(surveyAnswer);
        }
        try {
            surveyAnswerModel.insertBatch(list);
        }catch (Exception e){
            e.printStackTrace();
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.DATA_SAVING_ERROR);
        }

        return null;
    }
}
